﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Game.Contract.Action;
using ZyGames.Framework.Game.Lang;
using ZyGames.Framework.Game.Service;
using System.Linq;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Script;
using ZyGames.Framework.Net;
using ZyGames.Framework.Common.Serialization;
using System.Threading;
using ZyGames.Framework.Common.Log;
using ZyGames.DZPocker.Tools;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 玩家申请筹码
	/// </summary>
	public class Action30050 : BaseAction
	{
		private int tableId;
		private int userId;
		/// <summary>
		/// 申请的筹码数量,最大筹码数量是带入数量的两倍,  如果applychip为0则表示只是点击了左上方功能入口的申请按钮，下发result结果之后会弹出结果按钮
		/// </summary>
		private int applychip;

		private TableData _currentTable;
		private GameUser _currentGameUser;

		public Action30050(HttpGet actionGetter)
			: base((short)ActionType.DZApplyChip, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("TableId", ref tableId) &&
				httpGet.GetInt("UserId", ref userId) &&
				httpGet.GetInt("ApplyChip", ref applychip))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			_currentTable = GameRoom.Current.GetTableData(tableId);
			if (_currentTable == null)
			{
				Tool.WriteWarmingLine("消息30050获得房间不存在");
				return false;
			}
			_currentGameUser = GameTable.Current.GetUser(userId);
			if (_currentGameUser == null)
			{
				Tool.WriteWarmingLine("消息30050玩家不存在");
				return false;
			}
			//如果玩家正在当前桌子正在玩的话则不弹出申请筹码的弹框
			if (!_currentGameUser.Property.TableIdList.Contains(tableId))
			{
				Tool.WriteWarmingLine("当前玩家不在这个桌子里面，不好申请筹码");
				return false;
			}
			int PositionId;
			if (_currentGameUser.Property.PositionId.TryGetValue(tableId, out PositionId))
			{
				if (PositionId != 0)
				{
					var tempPos = _currentTable.Positions[PositionId - 1];
					if(tempPos == null)
					{
						Tool.WriteWarmingLine("位置不存在");
						return false;
					}
					else
					{
						if(tempPos.Chip > 0)
						{
							Tool.WriteWarmingLine("当前玩家还有筹码，不好申请筹码");
							return false;
						}
						else
						{
							Tool.WriteWarmingLine("当前玩家没有筹码可以申请筹码");
						}
					}
				}
			}
			if ((_currentTable.PlayerApplyChipControlSwitch && applychip > _currentTable.Chip * _currentTable.MaxMultiple) || (!_currentTable.PlayerApplyChipControlSwitch && applychip > _currentTable.Chip * 2) || applychip < 0)
			{
				Tool.WriteWarmingLine(string.Format("桌子:{0} 位置:{1} 申请的筹码超过当前房间默认筹码的2倍，被驳回申请"));
				return false;
			}
			else if (applychip == 0)
			{
				//如果当前玩家已经有筹码则不允许申请
				//剩余的筹码都要加到当前座位上
				RealTimeRecord record = _currentTable.GetRealTimeRecord(userId);
				if (record == null || record.LeftChip <= 0)
				{
					var maxApplyChip = _currentTable.Chip * 2;
					if (_currentTable.PlayerApplyChipControlSwitch)
						maxApplyChip = _currentTable.Chip * _currentTable.MaxMultiple;
					//发送DZShowApplyChipInfoTip消息给申请人，弹出申请弹框
					var param = new Parameters();
					param["TableId"] = _currentTable.TableId;
					param["MinApplyChip"] = _currentTable.Chip;
					param["MaxApplyChip"] = maxApplyChip;
					param["TableName"] = _currentTable.TableName;
					param["SmallChip"] = _currentTable.BindLevelCost.SmallBind;
					param["BigChip"] = _currentTable.BindLevelCost.SmallBind * 2; 
					param["DefaultChip"] = _currentTable.Chip; //默认带入
					GameTable.Current.SyncNotifyAction((int)ActionType.DZShowApplyChipInfoTip, _currentGameUser, param, t =>
					{
						Tool.WriteLine(string.Format("消息30051 弹出申请弹框 桌子:{0} 玩家:{1} 弹出申请弹框", _currentTable.TableId, userId));
					});
				}
				else
				{
					Tool.WriteWarmingLine("当前还存在筹码，不好申请");
					return false;
				}
			}
			else  //申请筹码发送给房主审核
			{
				if (_currentTable.TableMaster == null)
				{
					Tool.WriteErrorLine(string.Format("桌子:{0} 房主不存在", _currentTable.TableId));
					return false;
				}
				if (userId == _currentTable.TableMaster.GetUserId() || _currentTable.ApplyChipWithoutConfirmUserIDList.Contains(userId))
				{
					Tool.WriteWarmingLine("当前房主自己申请筹码 或者是特权玩家");

					//如果当前玩家是站起状态,添加到leftchip中，如果是坐下状态直接添加到座位的chip
					bool sit = false;
					foreach (var pos in _currentTable.Positions)
					{
						if (pos.UserId == userId)
						{
							if (!_currentTable.AddRealTimeRecord(userId, applychip, 0))
							{
								Tool.WriteErrorLine(string.Format("消息 30050 当前玩家坐下状态 房主处理玩家申请筹码 异常 桌子:{0} UserId:{1}", tableId, userId));
								return false;
							}
							sit = true;
							pos.Chip += applychip;
							//同步所有玩家的筹码
							GameTable.Current.SyncAllChip(_currentTable);
							if (_currentTable.State == TableState.Waiting)
								//判断是否已经开局，没有开局则开局
								GameTable.Current.CheckStart(_currentTable);
							break;
						}
					}
					if (!sit) //没有坐下则直接添加到玩家的left筹码中
					{
						if (!_currentTable.AddRealTimeRecord(userId, applychip, applychip))
						{
							Tool.WriteErrorLine(string.Format("消息 30050 当前玩家站起状态 房主处理玩家申请筹码 异常 桌子:{0} UserId:{1}", tableId, userId));
							return false;
						}
					}

					var parameters = new Parameters();
					parameters["TableId"] = tableId;
					parameters["UserId"] = userId;
					parameters["UserName"] = _currentGameUser.GetNickName();
					parameters["ApplyChip"] = applychip;
					GameTable.Current.SyncNotifyAction((int)ActionType.DZBrocastAuditApplyChipResult, _currentTable, parameters, t =>
					{
						Tool.WriteLine("广播消息30054 房主响应玩家申请筹码请求");
					});
				}
				else
				{
					if (_currentTable.ApplyChipRecore.ContainsKey(userId))
					{
						_currentTable.ApplyChipRecore[userId] = applychip;
					}
					else
					{
						_currentTable.ApplyChipRecore.Add(userId, applychip);
					}

					//玩家申请筹码，给房主发送消息DZAuditApplyChipInfoTip，审核批准
					var param = new Parameters();
					param["TableId"] = _currentTable.TableId;
					param["UserId"] = _currentGameUser.GetUserId();
					param["UserName"] = _currentGameUser.GetNickName();
					param["ApplyChip"] = applychip;
					GameTable.Current.SyncNotifyAction((int)ActionType.DZAuditApplyChipInfoTip, _currentTable.TableMaster, param, t =>
					{
						Tool.WriteLine(string.Format("消息30052 弹出房主处理玩家申请筹码消息桌子:{0} 玩家ID:{1} 处理申请筹码", _currentTable.TableId, userId));
					});
				}
			}
			return true;
		}
	}
}
